<template>
  <div class="submission-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="form-info">
          <h2>{{ formData.title || '表单数据' }}</h2>
          <p v-if="formData.description">{{ formData.description }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-button icon="Download" @click="exportData" :loading="exporting">导出数据</el-button>
        <el-button icon="RefreshRight" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ total }}</div>
          <div class="stat-label">总提交数</div>
        </div>
        <el-icon class="stat-icon" size="48"><Document /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ todayCount }}</div>
          <div class="stat-label">今日提交</div>
        </div>
        <el-icon class="stat-icon" size="48"><Calendar /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ weekCount }}</div>
          <div class="stat-label">本周提交</div>
        </div>
        <el-icon class="stat-icon" size="48"><PieChart /></el-icon>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form ref="searchFormRef" :inline="true" :model="searchInfo" class="search-form">
        <el-form-item v-if="!route.params.id" label="选择表单">
          <el-select 
            v-model="searchInfo.formId" 
            placeholder="请选择表单"
            filterable
            clearable
            @change="onFormChange"
            style="width: 200px"
          >
            <el-option
              v-for="form in formList"
              :key="form.ID"
              :label="form.title"
              :value="form.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchInfo.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onSearch"
          />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input 
            v-model="searchInfo.submitUser" 
            placeholder="输入用户ID" 
            clearable 
            @clear="onSearch"
            @keyup.enter="onSearch"
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input 
            v-model="searchInfo.submitIp" 
            placeholder="输入IP地址" 
            clearable 
            @clear="onSearch"
            @keyup.enter="onSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="onSearch">搜索</el-button>
          <el-button icon="Refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>提交数据列表</span>
          <div class="table-actions">
            <el-button 
              v-if="selectedSubmissions.length > 0" 
              type="danger" 
              icon="Delete" 
              @click="batchDelete"
            >
              批量删除 ({{ selectedSubmissions.length }})
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        v-loading="loading"
        :data="tableData" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="提交ID" prop="ID" width="80" sortable="custom" />
        
        <!-- 如果没有指定表单，显示表单名称列 -->
        <el-table-column v-if="!route.params.id" label="所属表单" width="150">
          <template #default="scope">
            <el-tag>{{ getFormName(scope.row.formId) || '表单' + scope.row.formId }}</el-tag>
          </template>
        </el-table-column>
        
        <!-- 动态渲染表单字段列 -->
        <el-table-column 
          v-for="field in formFields" 
          :key="field.id"
          :label="field.label"
          :min-width="getColumnWidth(field.type)"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div class="field-value">
              {{ formatFieldValue(scope.row.submitData, field) }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="提交用户" width="120">
          <template #default="scope">
            <span v-if="scope.row.submitUser">用户ID: {{ scope.row.submitUser }}</span>
            <el-tag v-else type="info" size="small">匿名用户</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="IP地址" prop="submitIp" width="140" />
        
        <el-table-column label="提交时间" prop="CreatedAt" width="160" sortable="custom">
          <template #default="scope">
            {{ formatDateTime(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="viewSubmission(scope.row)">查看</el-button>
            <el-button type="danger" link icon="Delete" @click="deleteSubmission(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchInfo.page"
          v-model:page-size="searchInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="提交详情" 
      width="800px"
      destroy-on-close
    >
      <div v-if="currentSubmission" class="submission-detail">
        <div class="detail-header">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="提交ID">{{ currentSubmission.ID }}</el-descriptions-item>
            <el-descriptions-item label="所属表单" v-if="!route.params.id">
              <el-tag>{{ getFormName(currentSubmission.formId) || '表单' + currentSubmission.formId }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="提交用户">
              <span v-if="currentSubmission.submitUser">用户ID: {{ currentSubmission.submitUser }}</span>
              <el-tag v-else type="info" size="small">匿名用户</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentSubmission.submitIp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ formatDateTime(currentSubmission.CreatedAt) }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="detail-content">
          <h3>提交内容</h3>
          <div class="form-data">
            <!-- 如果有字段定义，按照字段显示 -->
            <div v-if="detailFormFields.length > 0">
              <div v-for="field in detailFormFields" :key="field.id" class="field-item">
                <label class="field-label">{{ field.label || field.id }}:</label>
                <div class="field-value">
                  {{ formatFieldValue(currentSubmission.submitData, field) }}
                </div>
              </div>
            </div>
            <!-- 如果没有字段定义，显示原始数据 -->
            <div v-else>
              <div v-for="(value, key) in currentSubmission.submitData" :key="key" class="field-item">
                <label class="field-label">{{ key }}:</label>
                <div class="field-value">
                  {{ Array.isArray(value) ? value.join(', ') : value }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="danger" @click="deleteCurrentSubmission">删除此提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Download, RefreshRight, Document, Calendar, PieChart,
  Search, Refresh, Delete, View
} from '@element-plus/icons-vue'
import { 
  getSubmissionList, 
  getSubmission, 
  deleteSubmission as deleteSubmissionApi,
  getForm,
  getFormList,
  exportSubmissions
} from '@/plugin/gva_intelligent_form/api/form.js'

const route = useRoute()
const router = useRouter()

// 基础数据
const formData = ref({})
const formFields = ref([])
const formList = ref([]) // 表单列表（用于选择器）
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const exporting = ref(false)

// 统计数据
const todayCount = ref(0)
const weekCount = ref(0)

// 搜索条件
const searchInfo = ref({
  page: 1,
  pageSize: 20,
  formId: route.params.id ? parseInt(route.params.id) : undefined,
  dateRange: null,
  submitUser: '',
  submitIp: ''
})

// 选中的提交记录
const selectedSubmissions = ref([])

// 详情弹窗
const detailDialogVisible = ref(false)
const currentSubmission = ref(null)
const detailFormFields = ref([])

// 获取列宽度
const getColumnWidth = (fieldType) => {
  const widthMap = {
    'text': 150,
    'textarea': 200,
    'email': 180,
    'phone': 130,
    'number': 100,
    'radio': 120,
    'checkbox': 180,
    'select': 120,
    'date': 120,
    'rating': 100,
    'file': 200,
    'location': 150
  }
  return widthMap[fieldType] || 150
}

// 格式化字段值
const formatFieldValue = (submitData, field) => {
  if (!submitData) {
    return '-'
  }
  
  // 尝试多种可能的键名模式
  let value = submitData[field.id] || 
              submitData[field.key] || 
              submitData[field.fieldKey] ||
              submitData[`field_${field.id}`] ||  // 匹配 field_1, field_2 等格式
              submitData[field.id.toString()]
  
  if (value === null || value === undefined) {
    return '-'
  }
  
  switch (field.type) {
    case 'checkbox':
      return Array.isArray(value) ? value.join(', ') : value
    case 'file':
      if (Array.isArray(value)) {
        return value.map(file => file.name || file).join(', ')
      }
      return value.name || value
    case 'rating':
      return `${value}/5`
    case 'date':
      return new Date(value).toLocaleDateString()
    default:
      return value
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 获取表单名称
const getFormName = (formId) => {
  const form = formList.value.find(f => f.ID === formId)
  return form ? form.title : null
}

// 格式化提交数据（当没有字段定义时使用）
const formatSubmitData = (submitData) => {
  if (!submitData) return '无数据'
  return '点击查看详情'
}

// 加载表单信息
const loadFormInfo = async () => {
  if (!route.params.id) {
    // 如果没有指定表单ID，设置默认信息
    formData.value = {
      title: '所有表单数据',
      description: '查看所有表单的提交数据'
    }
    formFields.value = []
    return
  }
  
  try {
    const res = await getForm({ id: parseInt(route.params.id) })
    if (res.code === 0) {
      formData.value = res.data
      const formConfig = res.data.formConfig || {}
      formFields.value = formConfig.fields || []
      

    }
  } catch (error) {
    ElMessage.error('加载表单信息失败：' + error.message)
  }
}

// 加载提交数据
const loadSubmissions = async () => {
  loading.value = true
  
  try {
    const params = {
      page: searchInfo.value.page,
      pageSize: searchInfo.value.pageSize,
      formId: searchInfo.value.formId || 0
    }
    
    // 处理日期范围
    if (searchInfo.value.dateRange && searchInfo.value.dateRange.length === 2) {
      params.startCreatedAt = searchInfo.value.dateRange[0]
      params.endCreatedAt = searchInfo.value.dateRange[1]
    }
    
    // 处理其他查询条件
    if (searchInfo.value.submitUser) {
      params.submitUser = searchInfo.value.submitUser
    }
    if (searchInfo.value.submitIp) {
      params.submitIp = searchInfo.value.submitIp
    }
        
    const res = await getSubmissionList(params)
    if (res.code === 0) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
      

      
      // 计算统计数据
      calculateStats()
    }
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = () => {
  const today = new Date()
  const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const weekStart = new Date(todayStart.getTime() - 6 * 24 * 60 * 60 * 1000)
  
  todayCount.value = tableData.value.filter(item => 
    new Date(item.CreatedAt) >= todayStart
  ).length
  
  weekCount.value = tableData.value.filter(item => 
    new Date(item.CreatedAt) >= weekStart
  ).length
}

// 搜索
const onSearch = () => {
  searchInfo.value.page = 1
  loadSubmissions()
}

// 重置搜索
const onReset = () => {
  searchInfo.value = {
    page: 1,
    pageSize: searchInfo.value.pageSize,
    formId: route.params.id ? parseInt(route.params.id) : undefined,
    dateRange: null,
    submitUser: '',
    submitIp: ''
  }
  loadSubmissions()
}

// 表单选择变化
const onFormChange = async () => {
  // 重新加载表单信息和字段配置
  if (searchInfo.value.formId) {
    try {
      const res = await getForm({ id: searchInfo.value.formId })
      if (res.code === 0) {
        formData.value = res.data
        const formConfig = res.data.formConfig || {}
        formFields.value = formConfig.fields || []
      }
    } catch (error) {
      console.error('加载表单信息失败:', error)
    }
  } else {
    formData.value = {
      title: '所有表单数据',
      description: '查看所有表单的提交数据'
    }
    formFields.value = []
  }
  
  // 重新加载数据
  onSearch()
}

// 加载表单列表
const loadFormList = async () => {
  try {
    const res = await getFormList({ page: 1, pageSize: 1000 })
    if (res.code === 0) {
      formList.value = res.data.list || []
    }
  } catch (error) {
    console.error('加载表单列表失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  loadSubmissions()
}

// 分页处理
const handleSizeChange = (val) => {
  searchInfo.value.pageSize = val
  searchInfo.value.page = 1
  loadSubmissions()
}

const handleCurrentChange = (val) => {
  searchInfo.value.page = val
  loadSubmissions()
}

// 排序处理
const sortChange = ({ column, prop, order }) => {
  if (order) {
    searchInfo.value.orderBy = prop
    searchInfo.value.order = order === 'ascending' ? 'asc' : 'desc'
  } else {
    delete searchInfo.value.orderBy
    delete searchInfo.value.order
  }
  loadSubmissions()
}

// 选择处理
const handleSelectionChange = (val) => {
  selectedSubmissions.value = val
}

// 查看详情
const viewSubmission = async (row) => {
  try {
    const res = await getSubmission({ id: row.ID })
    if (res.code === 0) {
      const submission = res.data
      let parsedSubmitData = {}

      if (submission.submitData) {
        if (typeof submission.submitData === 'string') {
          try {
            parsedSubmitData = JSON.parse(submission.submitData)
          } catch (e) {
            console.error('Failed to parse submitData JSON:', e)
            // Keep parsedSubmitData as {}
          }
        } else if (typeof submission.submitData === 'object' && submission.submitData !== null) {
          parsedSubmitData = submission.submitData
        }
      }

      currentSubmission.value = {
        ...submission,
        submitData: parsedSubmitData
      }
      

      
      // 确定要使用的字段定义
      let fieldsToUse = formFields.value
      
      // 如果是全局列表（formFields为空）且提交记录有关联的 formId，
      // 则尝试动态加载该特定表单的字段定义
      if (fieldsToUse.length === 0 && currentSubmission.value.formId) {
        try {
          const formRes = await getForm({ id: currentSubmission.value.formId })
          if (formRes.code === 0 && formRes.data.formConfig && formRes.data.formConfig.fields) {
            fieldsToUse = formRes.data.formConfig.fields
          }
        } catch (error) {
          console.error(`加载表单字段失败 (formId: ${currentSubmission.value.formId}):`, error)
        }
      }
      
      detailFormFields.value = fieldsToUse
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败：' + error.message)
  }
}

// 删除单个提交
const deleteSubmission = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条提交记录吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteSubmissionApi({ id: row.ID })
    ElMessage.success('删除成功')
    loadSubmissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 删除当前查看的提交
const deleteCurrentSubmission = async () => {
  if (!currentSubmission.value) return
  
  try {
    await ElMessageBox.confirm('确定要删除这条提交记录吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteSubmissionApi({ id: currentSubmission.value.ID })
    ElMessage.success('删除成功')
    detailDialogVisible.value = false
    loadSubmissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedSubmissions.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedSubmissions.value.length} 条记录吗？`, '批量删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const submission of selectedSubmissions.value) {
      await deleteSubmissionApi({ id: submission.ID })
    }
    
    ElMessage.success('批量删除成功')
    selectedSubmissions.value = []
    loadSubmissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败：' + error.message)
    }
  }
}

// 导出数据
const exportData = async () => {
  exporting.value = true
  
  try {
    const params = {
      formId: searchInfo.value.formId || 0
    }
    
    // 处理日期范围
    if (searchInfo.value.dateRange && searchInfo.value.dateRange.length === 2) {
      params.startDate = searchInfo.value.dateRange[0].toISOString().split('T')[0]
      params.endDate = searchInfo.value.dateRange[1].toISOString().split('T')[0]
    }
    
    const response = await exportSubmissions(params)
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 清理文件名，移除非法字符
    const safeTitle = (formData.value.title || '表单数据').replace(/[<>:"/\\|?*]/g, '_')
    link.download = `${safeTitle}_${new Date().toISOString().split('T')[0]}.xlsx`
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  } finally {
    exporting.value = false
  }
}

// 返回
const goBack = () => {
  router.push({ name: 'formList' })
}

onMounted(() => {
  loadFormInfo()
  // 如果没有指定表单ID，先加载表单列表
  if (!route.params.id) {
    loadFormList()
  }
  loadSubmissions()
})
</script>

<style scoped>
.submission-list {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.form-info h2 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-info p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: default;
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  color: #409eff;
  opacity: 0.3;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

/* 表格卡片 */
.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.field-value {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 详情弹窗 */
.submission-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 24px;
}

.detail-content h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-data {
  display: grid;
  gap: 16px;
}

.field-item {
  display: flex;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.field-label {
  min-width: 120px;
  font-weight: 500;
  color: #495057;
  margin-right: 12px;
}

.field-value {
  flex: 1;
  color: #212529;
  word-break: break-word;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .submission-list {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-left {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .field-item {
    flex-direction: column;
  }
  
  .field-label {
    min-width: auto;
    margin-right: 0;
    margin-bottom: 4px;
  }
}
</style> 